<template>
  <HeaderComponent />
  <div class="main">
    <!-- 新增文章 -->
    <div class="container flex-container">
      <div class="title">
        <h3 class="title-text">发布文章</h3>
      </div>
      <!-- 给表单添加内边距 -->
      <el-form :model="form" class="custom-form">
        <el-form-item label="标签">
          <el-select v-model="form.tag" placeholder="请选择标签" class="full-width">
            <el-option label="求助打听" value="求助打听" />
            <el-option label="投稿爆料" value="投稿爆料" />
            <el-option label="社团招新" value="社团招新" />
            <el-option label="二手闲置" value="二手闲置" />
            <el-option label="代拿代办" value="代拿代办" />
          </el-select>
        </el-form-item>
        <el-form-item label="附图">
          <el-upload 
            class="custom-upload full-width"
            :auto-upload="false"
            :show-file-list="false"
            @change="handleFileChange"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <input type="file" style="display: none"/>
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="form.desc"
            :rows="5"
            type="textarea"
            placeholder="分享内容"
            class="full-width"
          />
        </el-form-item>
      </el-form>
      <div class="button-container">
        <el-button type="primary" @click="submit" class="custom-button"> 发布 </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import HeaderComponent from "../../components/HeaderComponent.vue";
import { ElMessage } from "element-plus";
import api from "../../utils/index.js"; 
import userStore from "../../store/index";
import { useRoute, useRouter } from "vue-router";
const userStoreInfo = userStore();
const user = userStoreInfo.getUser(); 
const route = useRoute();
const router = useRouter();
//文章内容
const form = reactive({
  tag: "",
  desc: "",
  img: ""
});

const articleId = route.query.id;
const articleInfo = ref({});

const fetchArticle = async () => {
  if (articleId) {
    try {
      const article = await api.get(`/articles/${articleId}`);
      articleInfo.value = article.data;
      form.tag = article.data.tag;
      form.desc = article.data.content;
    } catch (error) {
      console.error("Error fetching article:", error);
    }
  }
};

onMounted(fetchArticle);

// 处理文件选择
const handleFileChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.img = e.target.result 
  }
  reader.readAsDataURL(file.raw)
}

const submit = async () => {
  try {
    if (articleId) {
      await api.patch(`/articles/${articleId}`, {
        tag: form.tag,
        content: form.desc,
      });
      ElMessage.success("修改成功");
      setTimeout(() => {
        router.push({ path: "/articleinfo", query: { id: articleId } });
      }, 1000);
    } else {
      // 发送创建文章的请求
      const response = await api.post(`/articles`, {
        user_id: user.id,
        tag: form.tag,
        img: form.img, 
        content: form.desc,
        likes: 0,
        comments: 0,
        share: 0,
        time: new Date().toISOString().split("T")[0],
        like: [],
      });
      // 假设后端返回的数据中包含新文章的 id
      const newArticleId = response.data.id; 
      ElMessage.success("发布成功");
      // 跳转到文章详情页
      router.push({ path: "/articleinfo", query: { id: newArticleId } });
    }
  } catch (error) {
    console.error("Error submitting form:", error);
  }
};
</script>

<style scoped>
.main {
  padding-top: 20px;
  background-color: #f8f9fa;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.flex-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.container {
  border-radius: 16px;
  width: 80%;
  max-width: 700px; 
  margin: 0 auto;
  background-color: #fff;
  padding: 38px 40px 40px 40px; 
  box-shadow:0px 0px 12px rgba(0,0,0,0.12);
}

.title-text {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 32px; 
  font-size: 24px; 
}

.custom-form {
  width: 100%;
  margin-bottom: 32px; 
}

.full-width {
  width: 100%; 
}

.custom-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  transition: border-color 0.3s ease;
  min-height: 150px; 
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-upload:hover {
  border-color: #1890ff;
}

.avatar {
  max-width: 100%;
  max-height: 100%;
}

.button-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.custom-button {
  border-radius: 8px;
  padding: 10px 30px; 
  font-size: 16px;
  transition: opacity 0.3s ease;
  min-width: 150px; 
}

.custom-button:hover {
  opacity: 0.9;
}
</style>
